import React from 'react';
import ProForm, {
    ModalForm,
    ModalFormProps,
    ProFormText,
    ProFormDatePicker,
    ProFormSelect,
    ProFormDigit,
} from '@ant-design/pro-form';
import {useUpdateEffect} from 'ahooks';
import type {ProSchema} from '@ant-design/pro-utils';

const layout = {
    labelCol: {span: 4},
    wrapperCol: {span: 18},
};

export interface EditFormProps extends ModalFormProps {
    varietyEnum: ProSchema['valueEnum'];
    onCancel: () => void;
    type: string;
}

export const ADD_TYPE = '1';
export const EDIT_TYPE = '2';

export const type2title = {
    [ADD_TYPE]: '新建猫咪',
    [EDIT_TYPE]: '编辑猫咪',
};

const EditForm: React.FC<EditFormProps> = props => {
    const {varietyEnum, onFinish, visible, onCancel, type, initialValues} = props;

    const [form] = ProForm.useForm();

    useUpdateEffect(() => {
        if (type === EDIT_TYPE) {
            const {id, name, color, age, variety, birthday} = initialValues;
            form.setFieldsValue({
                id,
                name,
                color,
                age,
                variety,
                birthday
            });
        } else if (type === ADD_TYPE) {
            form.resetFields();
        }
    }, [initialValues, type]);

    return (
        <ModalForm<{
            name: string;
            color: string;
            variety: string;
            birthday: number;
        }>
            form={form}
            width={600}
            layout="horizontal"
            title={type2title[type]}
            visible={visible}
            trigger={null}
            onFinish={onFinish}
            dateFormatter="number"
            {...layout}
            modalProps={{
                onCancel
            }}
        >
            <ProFormText name="name" label="猫名" />
            <ProFormText name="color" label="颜色" />
            <ProFormDigit name="age" label="年龄" fieldProps={{precision: 0}} />
            <ProFormSelect
                name="variety"
                label="品种"
                valueEnum={varietyEnum}
            />
            <ProFormDatePicker name="birthday" label="出生日期" />
        </ModalForm>
    );
};

export default EditForm;
